class A:def method_A(self):return"Method from class A"class B:def method_B(self):return"Method from class B"class C(A, B):def method_C(self):return"Method from class C"# Creating instanceobj_C = C()# Demonstrating Multiple Inheritanceprint(obj_C.method_A()) # Output: Method from class Aprint(obj_C.method_B()) # Output: Method from class Bprint(obj_C.method_C()) # Output: Method from class C
Method from class A
Method from class B
Method from class C
3. Multilevel Inheritance Example:
class Vehicle:def display_type(self):return"Vehicle"class Car(Vehicle):def display_type(self):return"Car"class Sedan(Car):def display_type(self):return"Sedan"# Creating instancesedan_instance = Sedan()# Demonstrating Multilevel Inheritanceprint(sedan_instance.display_type()) # Output: Sedan
Name: Python Programming
Number of Authors: 1
Authors: John Doe
Publisher: Tech Publications
ISBN: 978-0-123456-78-9
Year: 2022
Course: Computer Science
Hierarchy 2: Staff, Teaching, and NonTeaching Classes
Name: John Smith
Salary: $50000
Subject: Mathematics
Name: Jane Doe
Salary: $45000
Department: Administration
Student class
Create a class called Student, having name and email as its data members and init(self, name, email) and putdata(self) as bound methods. The init function should assign the values passed as parameters to the requisite variables. The putdata function should display the data of the student. Create another class called PhDguide having name, email, and students as its data members. Here, the students variable is the list of students under the guide. The PhDguide class should have four bound methods: init, putdata, add, and remove. The init method should initialize the variables, the putdata should show the data of the guide, include the list of students, the add method should add a student to the list of students of the guide and the remove function should remove the student (if the student exists in the list of students of that guide) from the list of students.
class Student:def__init__(self, name, email):self.name = nameself.email = emaildef putdata(self):print(f"Student Name: {self.name}")print(f"Student Email: {self.email}")class PhDguide:def__init__(self, name, email):self.name = nameself.email = emailself.students = []def putdata(self):print(f"Guide Name: {self.name}")print(f"Guide Email: {self.email}")print("Students under the guide:")for student inself.students: student.putdata()print("---")def add(self, student):if student notinself.students:self.students.append(student)print(f"{student.name} added to the guide.")def remove(self, student):if student inself.students:self.students.remove(student)print(f"{student.name} removed from the guide.")else:print(f"{student.name} is not under the guide.")# Example Usagestudent1 = Student("Alice", "alice@example.com")student2 = Student("Bob", "bob@example.com")guide = PhDguide("Dr. Smith", "smith@example.com")guide.add(student1)guide.add(student2)guide.putdata()guide.remove(student1)guide.putdata()
Alice added to the guide.
Bob added to the guide.
Guide Name: Dr. Smith
Guide Email: smith@example.com
Students under the guide:
Student Name: Alice
Student Email: alice@example.com
---
Student Name: Bob
Student Email: bob@example.com
---
Alice removed from the guide.
Guide Name: Dr. Smith
Guide Email: smith@example.com
Students under the guide:
Student Name: Bob
Student Email: bob@example.com
---
invoking __init__() in case of multiple inheritance:
class A:def__init__(self):print("Initializing class A")class B:def__init__(self):print("Initializing class B")class C(A, B):def__init__(self):super().__init__()# Creating an instance of class Cobj_c = C()
Initializing class A
Distance and Slope between two points in Cartesian coordinate system:
class Student:def__init__(self, roll_no, name, age, total_marks):self.roll_no = roll_noself.name = nameself.age = ageself.total_marks = total_marksdef__eq__(self, other):returnself.total_marks == other.total_marksdef display_info(self):print(f"Roll No: {self.roll_no}")print(f"Name: {self.name}")print(f"Age: {self.age}")print(f"Total Marks: {self.total_marks}")# Example usagestudent1 = Student(1, "Alice", 20, 85)student2 = Student(2, "Bob", 22, 85)if student1 == student2:print("Students have the same marks.") student1.display_info() student2.display_info()else:print("Students do not have the same marks.")
Students have the same marks.
Roll No: 1
Name: Alice
Age: 20
Total Marks: 85
Roll No: 2
Name: Bob
Age: 22
Total Marks: 85
Overloading > and < operators for the Data class:
class Data:def__init__(self, value):self.value = valuedef__lt__(self, other):returnself.value < other.valuedef__gt__(self, other):returnself.value > other.value# Example usagedata1 = Data(5)data2 = Data(10)if data1 > data2:print("data1 is greater than data2.")elif data1 < data2:print("data1 is less than data2.")else:print("data1 is equal to data2.")
data1 is less than data2.
Instantiating class with or without arguments:
class Data:def__init__(self, value=None):if value isnotNone:self.value = valueprint("True: Object initialized with value")else:print("False: Object initialized without value")# Example usageobj1 = Data(5) # True: Object initialized with valueobj2 = Data() # False: Object initialized without value
True: Object initialized with value
False: Object initialized without value
Create a 5X2 integer array from a range between 100 to 200 such that the difference between each element is 10
import numpy as nparr = np.arange(100, 200, 10).reshape(5, 2)print("5x2 Array:")print(arr)
import numpy as npsampleArray = np.array([[11, 22, 33], [44, 55, 66], [77, 88, 99]])third_column = sampleArray[:, 2]print("Array of items from the third column:")print(third_column)
Array of items from the third column:
[33 66 99]
“Return array of odd rows and even columns from below numpy array
import numpy as npsampleArray = np.array([[3, 6, 9, 12], [15, 18, 21, 24], [27, 30, 33, 36], [39, 42, 45, 48], [51, 54, 57, 60]])odd_rows_even_columns = sampleArray[::2, 1::2]print("Array of odd rows and even columns:")print(odd_rows_even_columns)
Array of odd rows and even columns:
[[ 6 12]
[30 36]
[54 60]]
“Sort following NumPy array
Case 1: Sort array by the second row
Case 2: Sort the array by the second column
sampleArray = numpy.array([[34,43,73],[82,22,12],[53,94,66]])”
import numpy as npsampleArray = np.array([[34, 43, 73], [82, 22, 12], [53, 94, 66]])# Case 1: Sort array by the second rowsorted_by_second_row = sampleArray[:, sampleArray[1, :].argsort()]# Case 2: Sort the array by the second columnsorted_by_second_column = sampleArray[sampleArray[:, 1].argsort()]print("Sorted array by the second row:")print(sorted_by_second_row)print("\nSorted array by the second column:")print(sorted_by_second_column)
Sorted array by the second row:
[[73 43 34]
[12 22 82]
[66 94 53]]
Sorted array by the second column:
[[82 22 12]
[34 43 73]
[53 94 66]]
“Print max from axis 0 and min from axis 1 from the following 2-D array.
import numpy as npsampleArray = np.array([[34, 43, 73], [82, 22, 12], [53, 94, 66]])max_axis_0 = np.max(sampleArray, axis=0)min_axis_1 = np.min(sampleArray, axis=1)print("Max from axis 0:")print(max_axis_0)print("\nMin from axis 1:")print(min_axis_1)
Max from axis 0:
[82 94 73]
Min from axis 1:
[34 12 53]
Temperature program
“Write a NumPy array program to convert the values of Fahrenheit degrees into Celsius degrees. The numpy array to be considered is [0, 12, 45.21, 34, 99.91, 32] for Fahrenheit values. Values are stored into a NumPy array. After converting the following numpy array into Celsius, then sort the array and find the position of 0.0 (means where 0.0 value is located i.e. it’s index) Formula to convert value of Fahrenheit to Celsius is: C=5F/9 - 532/9 Output: Values in Fahrenheit degrees: [ 0. 12. 45.21 34. 99.91 32. ] Values in Centigrade degrees: [-17.77777778 -11.11111111 7.33888889 1.11111111 37.72777778 0. ] [-17.77777778 -11.11111111 0. 1.11111111 7.33888889 37.72777778] (array([2], dtype=int64),)”
import numpy as np# Fahrenheit arrayfahrenheit_array = np.array([0, 12, 45.21, 34, 99.91, 32])# Convert Fahrenheit to Celsius using the given formulacelsius_array = (fahrenheit_array -32) *5/9# Display original Fahrenheit and converted Celsius arraysprint("Values in Fahrenheit degrees:")print(fahrenheit_array)print("Values in Centigrade degrees:")print(celsius_array)# Sort the Celsius arraysorted_celsius_array = np.sort(celsius_array)# Find the position of 0.0 in the sorted arrayzero_position = np.where(sorted_celsius_array ==0.0)# Display the sorted array and the position of 0.0print(sorted_celsius_array)print(zero_position)
"Imagine you own a call center. Use the following abstract class template to create three more classes, Respondent, Manager, and Director that inherit this Employee Abstract Class.
from abc import ABC, abstractmethod
class Employee(ABC):
@abstractmethod
def receive_call(self):
pass
@abstractmethod
def end_call(self):
pass
@abstractmethod
def is_free(self):
pass
@abstractmethod
def get_rank(self):
pass
"
Create a program using the instructions given below: 1. Create a constructor in all three classes (Respondent, Manager and Director) which takes the id and name as input and initializes two additional variables, rank and free. rank should be equal to 3 for Respondent, 2 for Manager and 1 for Director. free should be a boolean variable with value True initially. (1 mark) 2. Implement rest of the methods in all three classes in the following way: (2 marks) a. receive_call(): prints the message, “call received by (name of the employee)” and sets the free variable to False. b. end_call(): prints the message, “call ended” and sets the free variable to True. c. is_free(): returns the value of the free variable d. get_rank(): returns the value of the rank variable 3. Create a class Call, with a constructor that accepts id and name of the caller and initializes a variable called assigned to False. (0.5 marks) 4. Create a class CallHandler, with three lists, respondents, managers and directors as class variables. (0.5 marks) 5. Create an add_employee() method in CallHandler class that allows you to add an employee (an object of Respondent/Manager/Director) into one of the above lists according to their rank. (1 mark) 6. Create a dispatch_call() method in CallHandler class that takes a call object as a parameter. This method should find the first available employee starting from rank 3, then rank 2 and then rank 1. If a free employee is found, call its receive_call() function and change the call’s assigned variable value to True. If no free employee is found, print the message: “Sorry! All employees are currently busy.” (2 marks) 7. Create 3 Respondent objects, 2 Manager objects and 1 Director object and add them into the list of available employees using the CallHandler’s add_employee() method. (1 mark) 8. Create a Call object and demonstrate how it is assigned to an employee. (1 mark) ”
Write a python program to create a Bus child class that inherits from the Vehicle class.
In Vehicle class vehicle name, mileage and seatingcapacity as its data member. The default fare charge of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge. So total fare for bus instance will become the final amount = total fare + 10% of the total fare.
Sample Output: The bus seating capacity is 50. so, the final fare amount should be 5000+500=5500.
The car seating capacity is 5. so, the final fare amount should be 500.”
class Vehicle:def__init__(self, name, mileage, seating_capacity):self.name = nameself.mileage = mileageself.seating_capacity = seating_capacitydef calculate_fare(self):returnself.seating_capacity *100class Bus(Vehicle):def__init__(self, name, mileage, seating_capacity):super().__init__(name, mileage, seating_capacity)def calculate_fare(self): base_fare =super().calculate_fare() maintenance_charge =0.1* base_fare final_fare = base_fare + maintenance_chargereturn final_fare# Example usage:bus_instance = Bus("Bus", 10, 50)car_instance = Vehicle("Car", 20, 5)bus_fare = bus_instance.calculate_fare()car_fare = car_instance.calculate_fare()print(f"The bus seating capacity is {bus_instance.seating_capacity}. "f"So, the final fare amount should be {bus_fare}.")print(f"The car seating capacity is {car_instance.seating_capacity}. "f"So, the final fare amount should be {car_fare}.")
The bus seating capacity is 50. So, the final fare amount should be 5500.0.
The car seating capacity is 5. So, the final fare amount should be 500.
Create an abstract class named Shape.
Create an abstract method named calculate_area for the Shape class. Create Two Classes named Rectangle and Circle which inherit Shape class. Create calculate_area method in Rectangle class. It should return the area of the rectangle object. (area of rectangle = (length * breadth)) Create calculate_area method in Circle class. It should return the area of the circle object. (area of circle =πr^2)) Create objects of Rectangle and Circle class. The python Program Should also check whether the area of one Rectangle object is greater than another rectangle object by overloading > operator. Execute the method resolution order of the Circle class. ”
from abc import ABC, abstractmethodimport mathclass Shape(ABC):@abstractmethoddef calculate_area(self):passclass Rectangle(Shape):def__init__(self, length, breadth):self.length = lengthself.breadth = breadthdef calculate_area(self):returnself.length *self.breadthdef__gt__(self, other):returnself.calculate_area() > other.calculate_area()class Circle(Shape):def__init__(self, radius):self.radius = radiusdef calculate_area(self):return math.pi * (self.radius **2)# Creating objects of Rectangle and Circle classrectangle1 = Rectangle(5, 10)rectangle2 = Rectangle(3, 8)circle = Circle(7)# Checking whether the area of one Rectangle object is greater than anotherif rectangle1 > rectangle2:print("Area of rectangle1 is greater than rectangle2.")else:print("Area of rectangle2 is greater than rectangle1.")# Printing the method resolution order of the Circle classprint(f"Method Resolution Order for Circle class: {Circle.mro()}")
Area of rectangle1 is greater than rectangle2.
Method Resolution Order for Circle class: [<class '__main__.Circle'>, <class '__main__.Shape'>, <class 'abc.ABC'>, <class 'object'>]
Write a python program to demonstrate the use of super() method to call the method of base class.
class Animal:def__init__(self, name):self.name = namedef speak(self):print(f"{self.name} makes a sound")class Dog(Animal):def__init__(self, name, breed):super().__init__(name)self.breed = breeddef speak(self):super().speak() # Calling the speak method of the base classprint(f"{self.name} barks loudly")# Create an instance of the Dog classdog_instance = Dog("Buddy", "Labrador")# Call the speak method of the Dog classdog_instance.speak()
Buddy makes a sound
Buddy barks loudly
Create a class called Matrix containing constructor that initialized the number of rows and number of columns of a new Matrix object.
The Matrix class has methods for each of the following: 1. get the number of rows 2. get the number of columns 3. set the elements of the matrix at given position (i,j) 4. adding two matrices. If the matrices are not addable, “ Matrices cannot be added” will be displayed.(Overload the addition operation to perform this) 5. Multiplying the two matrices. If the matrices are not multiplied, “ Matrices cannot be multiplied” will be displayed.(Overload the addition operation to perform this) ”
class Matrix:def__init__(self, rows, columns):self.rows = rowsself.columns = columnsself.matrix = [[0for _ inrange(columns)] for _ inrange(rows)]def get_rows(self):returnself.rowsdef get_columns(self):returnself.columnsdef set_element(self, i, j, value):if0<= i <self.rows and0<= j <self.columns:self.matrix[i][j] = valueelse:print("Invalid position. Cannot set element.")def add_matrices(self, other_matrix):ifself.rows == other_matrix.get_rows() andself.columns == other_matrix.get_columns(): result_matrix = Matrix(self.rows, self.columns)for i inrange(self.rows):for j inrange(self.columns): result_matrix.set_element(i, j, self.matrix[i][j] + other_matrix.matrix[i][j])return result_matrixelse:print("Matrices cannot be added.")def multiply_matrices(self, other_matrix):ifself.columns == other_matrix.get_rows(): result_matrix = Matrix(self.rows, other_matrix.get_columns())for i inrange(self.rows):for j inrange(other_matrix.get_columns()): result =0for k inrange(self.columns): result +=self.matrix[i][k] * other_matrix.matrix[k][j] result_matrix.set_element(i, j, result)return result_matrixelse:print("Matrices cannot be multiplied.")def__str__(self):return'\n'.join([' '.join(map(str, row)) for row inself.matrix])# Example usage:matrix1 = Matrix(2, 3)matrix2 = Matrix(3, 2)matrix1.set_element(0, 0, 1)matrix1.set_element(0, 1, 2)matrix1.set_element(0, 2, 3)matrix1.set_element(1, 0, 4)matrix1.set_element(1, 1, 5)matrix1.set_element(1, 2, 6)matrix2.set_element(0, 0, 7)matrix2.set_element(0, 1, 8)matrix2.set_element(1, 0, 9)matrix2.set_element(1, 1, 10)matrix2.set_element(2, 0, 11)matrix2.set_element(2, 1, 12)print("Matrix 1:")print(matrix1)print("\nMatrix 2:")print(matrix2)result_addition = matrix1.add_matrices(matrix2)print("\nMatrix Addition:")print(result_addition)result_multiplication = matrix1.multiply_matrices(matrix2)print("\nMatrix Multiplication:")print(result_multiplication)
“Write a Python Program to Find the Net Salary of Employee using Inheritance.
Create three Class Employee, Perks, NetSalary. Make an Employee class as an abstract class. Employee class should have methods for following tasks. - To get employee details like employee id, name and salary from user. - To print the Employee details. - return Salary. - An abstract method emp_id. Perks class should have methods for following tasks. - To calculate DA, HRA, PF. - To print the individual and total of Perks (DA+HRA-PF). Netsalary class should have methods for following tasks. - Calculate the total Salary after Perks. - Print employee detail also prints DA, HRA, PF and net salary.
Note 1: DA-35%, HRA-17%, PF-12% Note 2: It is compulsory to create objects and demonstrating the methods with Correct output. Example: Employee ID: 1 Employee Name: John Employee Basic Salary: 25000 DA: 8750.0 HRA: 4250.0 PF: 3000.0 Total Salary: 35000.0”
Enter Employee ID: 1
Enter Employee Name: John
Enter Employee Basic Salary: 25000
Employee ID: 1
Employee Name: John
Employee Basic Salary: 25000.0
DA: 8750.0
HRA: 4250.0
PF: 3000.0
Total Perks: 10000.0
Total Salary: 35000.0
UNIT 10 MATPLOTLIB LIBRARY
These cost categories applied to a $9.00 microcontroller:
Engineering $1.35
Manufacturing $3.60
Sales $2.25
Profit $1.80
Create a pie chart will show the cost breakdown as different sized pieces.
import matplotlib.pyplot as plt# Cost breakdowncost_categories = ['Engineering', 'Manufacturing', 'Sales', 'Profit']cost_values = [1.35, 3.60, 2.25, 1.80]# Create a pie chartplt.figure(figsize=(8, 8))plt.pie(cost_values, labels=cost_categories, autopct='%1.1f%%', startangle=140, colors=['skyblue', 'lightgreen', 'lightcoral', 'gold'])plt.title('Cost Breakdown for a $9.00 Microcontroller')plt.show()
These cost categories applied to a $9.00 microcontroller:
“Here is how many students got each grade in the recent test:
A- 4, B-12, C-10, D-2. Plot a pie chart for the student grades in the recent chart with different colors for each student grades and create a wedge for D. Also put a chart title as student’s grade history.”
import matplotlib.pyplot as plt# Student grades datagrades = ['A', 'B', 'C', 'D']students_count = [4, 12, 10, 2]# Colors for each gradecolors = ['lightgreen', 'skyblue', 'lightcoral', 'gold']# Create a pie chartplt.figure(figsize=(8, 8))plt.pie(students_count, labels=grades, autopct='%1.1f%%', startangle=140, colors=colors, explode=(0, 0, 0, 0.1))plt.title("Student's Grade History")# Display the pie chartplt.show()
“Here is how many students got each grade in the recent test:
Imagine you survey your friends to find the kind of movie they like best:
Comedy- 4, Action -5, Romance - 6, Drama -1, SciFi - 4. Plot a pie chart for the above survey and use different color for each analysis and create a wedge for action movies. Also put as chart title as “Survey analysis of movie”
import matplotlib.pyplot as plt# Movie preferences datagenres = ['Comedy', 'Action', 'Romance', 'Drama', 'SciFi']counts = [4, 5, 6, 1, 4]# Colors for each genrecolors = ['skyblue', 'lightcoral', 'lightgreen', 'gold', 'lightpink']# Create a pie chartplt.figure(figsize=(8, 8))explode = (0, 0.1, 0, 0, 0) # Explode the Action wedgeplt.pie(counts, labels=genres, autopct='%1.1f%%', startangle=140, colors=colors, explode=explode)plt.title("Survey Analysis of Movie Preferences")# Display the pie chartplt.show()
Create a Pie Chart using Python Program
for the popularity data of different programming languages and displayed it as a pie chart using the Matplotlib Python library. For Python- 29, Java – 19, Javascript – 8, C# - 7, PHP – 6, C,C++ - 5, R – 3. Create an exploded view of python and show the % of each programming language in Pie Chart.
import matplotlib.pyplot as plt# Programming languages datalanguages = ['Python', 'Java', 'Javascript', 'C#', 'PHP', 'C/C++', 'R']popularity = [29, 19, 8, 7, 6, 5, 3]# Explode Python wedgeexplode = [0.1if lang =='Python'else0for lang in languages]# Create a pie chartplt.figure(figsize=(8, 8))plt.pie(popularity, labels=languages, autopct='%1.1f%%', startangle=140, explode=explode, colors=plt.cm.Paired.colors)plt.title("Popularity of Programming Languages")# Display the pie chartplt.show()
“Write a python program to create a bar plot of
course v/s no. of students using the following dictionary with appropriate labels for X and Y axes and colour of the bars green. Data={‘C’:20,’C++’:15,’Java’:30,’Python’:35}”
import matplotlib.pyplot as plt# Datadata = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35}# Extracting labels and valuescourses =list(data.keys())students =list(data.values())# Create a bar plotplt.bar(courses, students, color='green')plt.xlabel('Courses')plt.ylabel('Number of Students')plt.title('Number of Students per Course')# Display the bar plotplt.show()
“Create a bar chart for the following dataset: Country = [‘USA’,‘Canada’,‘Germany’,‘UK’,‘France’]
GDP_Per_Capita = [45000,42000,52000,49000,47000]. Also plot title, X-Axis, Y-Axis, different color for each country and the grid should be visible”
import matplotlib.pyplot as plt# Datasetcountries = ['USA', 'Canada', 'Germany', 'UK', 'France']gdp_per_capita = [45000, 42000, 52000, 49000, 47000]# Create a bar chartplt.bar(countries, gdp_per_capita, color=['blue', 'orange', 'green', 'red', 'purple'])plt.xlabel('Country')plt.ylabel('GDP Per Capita')plt.title('GDP Per Capita by Country')plt.grid(True)# Display the bar chartplt.show()
A Bar Chart
to display employee id numbers on X-axis and their salaries as Y-axis in the form of a bar graph for two departments of a company. There are two departments like sales department and purchase department. For sales department their id’s and salaries are mentioned as : x= [1001,1003,1006,1007,1009,1011] and y= [10000, 23000.50,18000.33,16500.5,12000.75, 9999.99] and for purchase department their id’s and salaries are mentioned as: x=[100̣2,1004,1010,1008,1014,1015] and y=[ 5000,6000,4500.5,12000,9000,10000]. Make the chart title as “Microsoft Inc.”, x-axis as emplyee id and Y axis as Salary. Use different colors for sales and purchase department.
import matplotlib.pyplot as plt# Sales Department datasales_ids = [1001, 1003, 1006, 1007, 1009, 1011]sales_salaries = [10000, 23000.50, 18000.33, 16500.5, 12000.75, 9999.99]# Purchase Department datapurchase_ids = [1002, 1004, 1010, 1008, 1014, 1015]purchase_salaries = [5000, 6000, 4500.5, 12000, 9000, 10000]# Create a bar chartplt.bar(sales_ids, sales_salaries, color='blue', label='Sales Department', alpha=0.7)plt.bar(purchase_ids, purchase_salaries, color='green', label='Purchase Department', alpha=0.7)plt.xlabel('Employee ID')plt.ylabel('Salary')plt.title('Microsoft Inc.')plt.legend()plt.grid(True)# Display the bar chartplt.show()
Subplots of Bar Graphs for Two Dictionaries
import matplotlib.pyplot as plt# DataD1 = {"aryan": 66, "bob": 70, "jack": 66, "seema": 34}D2 = {"joy": 45, "sid": 85, "hina": 90}# Create subplotsfig, axs = plt.subplots(2, 1, figsize=(8, 8))# Bar plot for D1axs[0].bar(D1.keys(), D1.values(), color='blue')axs[0].set_title('Department 1')# Bar plot for D2axs[1].bar(D2.keys(), D2.values(), color='green')axs[1].set_title('Department 2')# Set common title for subplotsfig.suptitle('BAR PLOT')# Display the subplotsplt.show()
“Draw multiple plots in one figure using subplot function. The multiple plots include below according to order:
Plot a scatter plot with following data: x = [5,7,8,7,2,17,2,9,4,11,12,9,6] y = [99,86,87,88,111,86,103,87,94,78,77,85,86] The x axis represents the age of car while y axis represents the speed of car. The title of the graph should be age v/s speed of car. Also in graph there should be x and y labels. The marker used should be star. The marker color should be green. The marker size should be 60. (Entire Scatter plot 2 marks)
Plot a horizontal bar with following data: x=[““A”“,”“B”“,”“C”“,”“D””] y=[3, 8, 1, 10] The x axis represents the name of car while y axis represents the selling of car. The title of the graph should be name v/s selling of car. Also in graph there should be x and y label. The horizontal bar chart’s height should be 0.1. The color of bar should be yellow. (Entire bar plot 2 marks)
Plot a histogram with following data: data=[1,3,3,3,3,9,9,5,4,4,8,8,8,6,7] bins=4, the title of the graph should be histogram of cars. The orientation should be vertical. The color of plot should be violet (Entire histogram plot 2 marks)
Plot a pie with following data: y=[35,25,25,15] mylabels=[‘Apple’,‘Bananas’,‘Cherries’,‘Dates’] The title of the graph should be pie chart. The exploded view should be shown with 0.2 value for ‘Apple’ (Entire pie chart of 2 marks) Also need to provide a superior title to the subplot prepared i.e ‘My Subplot for cars’(0.5 marks) and subplot preparation (0.5 mark) For clear visualization can use the following syntax after importing matplotlib plt.figure(figsize=(10,10))
”
import matplotlib.pyplot as plt# Data for scatter plotx_scatter = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]y_scatter = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]# Data for horizontal bar plotx_bar = ["A", "B", "C", "D"]y_bar = [3, 8, 1, 10]# Data for histogramdata_hist = [1, 3, 3, 3, 3, 9, 9, 5, 4, 4, 8, 8, 8, 6, 7]bins_hist =4# Data for pie charty_pie = [35, 25, 25, 15]labels_pie = ['Apple', 'Bananas', 'Cherries', 'Dates']# Subplot preparationplt.figure(figsize=(10, 10))# Subplot 1: Scatter Plotplt.subplot(2, 2, 1)plt.scatter(x_scatter, y_scatter, marker='*', color='green', s=60)plt.title('Age vs Speed of Car')plt.xlabel('Age of Car')plt.ylabel('Speed of Car')# Subplot 2: Horizontal Bar Plotplt.subplot(2, 2, 2)plt.barh(x_bar, y_bar, height=0.1, color='yellow')plt.title('Name vs Selling of Car')plt.xlabel('Name of Car')plt.ylabel('Selling of Car')# Subplot 3: Histogramplt.subplot(2, 2, 3)plt.hist(data_hist, bins=bins_hist, orientation='vertical', color='violet')plt.title('Histogram of Cars')plt.xlabel('Cars')plt.ylabel('Frequency')# Subplot 4: Pie Chartplt.subplot(2, 2, 4)plt.pie(y_pie, labels=labels_pie, autopct='%1.1f%%', explode=[0.2, 0, 0, 0], startangle=90)plt.title('Pie Chart')# Superior Titleplt.suptitle('My Subplot for Cars')# Show the subplotplt.show()
“There is an array of scores of 5 Batsmen in 4 T20 Matches. Which is given below.
Scores= [[13, 10, 9, 33], [63, 46, 90, 42], [39, 76, 13, 29], [82, 9, 29, 78], [67, 61, 59, 36]] Further you are asked to perform below tasks. (i). Add scores of every batsman of 5th Match given below in the same array and print the array. Match_6= [41, 87, 72, 36, 92] (ii). Add two new batsmen’s scores in respective 5 T20 Matches in the array created in task (i) above and print the array. Batsman_6= [77, 83, 98, 95, 89] Batsman_7= [92, 71, 52, 61, 53] (iii). Add extra column with sum of all 5 T20 Matches’ scores of each batsman in the array created in task (ii) and print the final array. Note: Use Numpy module for all the Arrays given above. “Using the final array created in task(iii) above, generate graphs mentioned below: (a). Make a line chart of Total Scores of each batsman which is stored in last column of final array v/s No. of Batsman. Use dashed line in graph, with black color. Give label on x-axis as “No. of Batsman” and label on y-axis as “Scores”. Give title to the chart as “Leader Board” with bold fonts. (b). Make one Bar chart of scores of Batsman_1 and Batsman_2 for all 5 T20 matches. Give color for bars of Batsman_1 as Purple and for Batsman_2 Dark red. Also show required legend in bar chart. (c). Make a pie chart of Total Scores of each batsman which is stored in last column of final array. Show the pie chart with exploded view of all pieces with 0.1 amount. Also display percentage in the pie chart. Also show required legend for pie chart. Note: Passing the values using numpy Array Slicing from array created in task(iii) for creating graphs above is compulsory.”
import numpy as npimport matplotlib.pyplot as plt# Task (i)Scores = np.array([[13, 10, 9, 33], [63, 46, 90, 42], [39, 76, 13, 29], [82, 9, 29, 78], [67, 61, 59, 36]])Match_6 = np.array([41, 87, 72, 36, 92])# Append Match_6 as a new column to ScoresScores = np.append(Scores, Match_6.reshape(-1, 1), axis=1) # Append along columns (axis=1)print("Task (i):")print(Scores)print()# Task (ii)Batsman_6 = np.array([77, 83, 98, 95, 89])Batsman_7 = np.array([92, 71, 52, 61, 53])Scores = np.concatenate((Scores, Batsman_6.reshape(-1, 1), Batsman_7.reshape(-1, 1)), axis=1)print("Task (ii):")print(Scores)print()# Task (iii)Total_Scores = np.sum(Scores[:, :-2], axis=1)Scores = np.concatenate((Scores, Total_Scores.reshape(-1, 1)), axis=1)print("Task (iii):")print(Scores)print()# Graphs# (a) Line chartbatsman_numbers = np.arange(1, Scores.shape[0] +1) # Adjusted for the number of batsmentotal_scores = Scores[:, -1]plt.figure(figsize=(10, 6))plt.plot(batsman_numbers, total_scores, linestyle='dashed', color='black')plt.xlabel('No. of Batsman')plt.ylabel('Scores')plt.title('Leader Board', fontweight='bold')plt.show()# (b) Bar chartbatsman_1_scores = Scores[:, -4]batsman_2_scores = Scores[:, -3]plt.figure(figsize=(10, 6))plt.bar(batsman_numbers -0.2, batsman_1_scores, width=0.4, color='purple', label='Batsman_1')plt.bar(batsman_numbers +0.2, batsman_2_scores, width=0.4, color='darkred', label='Batsman_2')plt.xlabel('T20 Matches')plt.ylabel('Scores')plt.legend()plt.show()# (c) Pie chartlabels = [f'Batsman_{i}'for i inrange(1, Scores.shape[1] -2)] # Adjusted for the number of batsmenexplode = [0.1] *len(labels)plt.figure(figsize=(8, 8))plt.pie(total_scores, labels=labels, explode=explode, autopct='%1.1f%%', startangle=90)plt.title('Total Scores Distribution')plt.legend(labels, loc='upper left')plt.show()
“Write a program to build 6 graphs(3 row and 2 column) using subplot function for given data:
Subplot 1: Draw a line from (5,5) to (10,17) to (25,25) to (60,40) to (80,30) with suitable label in the x axis, y axis and a title. Line color should be green. Line style should be dotted. Marker should be diamond. Subplot 2: Write a Python program to create bar plot of scores by group and gender. Give suitable label in the x axis, y axis and a title. Colors of all label should be black and title should be bold. Color of bar plot of men and women scores should be green and red. Data: Scores_men = (22, 30, 35, 35, 26) Scores_women = (25, 32, 30, 35, 29) Subplot 3: Write a Python programming to create a pie chart with a title of the popularity of Car company. Make multiple wedges of the pie. Also show the percentage. data: Car : Maruti Suzuki, Hyundai, Kia, Toyota, Honda Popularity: 25,50,30,20,35 Subplot 4: Write a Python program to draw a scatter plot comparing two subject marks of Mathematics and Science. Use marks of 10 students. Marker of mathematics and science should be circle and star. Colors of marker of mathematics and science should be yellow and blue. Test Data: math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34] science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30] Subplot 5: Write a Python programming to display a horizontal bar chart of the popularity of programming Languages. Colors of all programming Languages should be different. Give suitable label in the x axis, y axis and a title. data: Programming languages: Java, Python, PHP, JavaScript, C, C++ Popularity: 20,100,25,30,45,50 Subplot 6: Write a Python programming to display a Histogram chart for given data. Color of chart should be red. Data=[10,20,20,30,30,30,40,40,40,40,50,50,50,60,60,70]”
Get total profit of all months and show line plot with the following Style properties:
• Line Style dotted and Line-color should be red • Show legend at the lower right location. • X label name = Month Number • Y label name = Total Profits • Add a circle marker • Line marker color as blue • Line marker size as 5 • Line width should be 3
import matplotlib.pyplot as plt# Month Number and Total Profit datamonth_numbers =list(range(1, 13))total_profits = [211000, 183300, 224700, 222700,209600, 201400, 295500, 361400,234000, 266700, 412800, 300200]plt.figure(figsize=(10, 5))plt.plot(month_numbers, total_profits, linestyle='dotted', color='red', marker='o', markerfacecolor='blue', markersize=5, linewidth=3, label='Total Profits')plt.xlabel('Month Number')plt.ylabel('Total Profits')plt.title('Total Profits of All Months')plt.legend(loc="lower right")plt.grid(True)plt.show()
There is an array of scores of 5 Batsmen in 4 T20 Matches. Which is given below.
Scores= [[31, 12, 19, 53],
[67, 48, 95, 83],
[59, 67, 13, 59],
[62, 29, 99, 88],
[87, 91, 69, 76]]
1. Find the maximum score in T_20-3 and print it (use only the numpy module)
2. Find the minimum score of YUVRAJ and print it (use only the numpy module)
3. Add an extra column with the sum of all 4 T20 Matches’ scores of each batsman in the array created and print it. (use only the numpy module)
import numpy as np# Sample scores arrayScores = np.array([[31, 12, 19, 53], [67, 48, 95, 83], [59, 67, 13, 59], [62, 29, 99, 88], [87, 91, 69, 76]])# 1. Find the maximum score in T_20-3 (index 2)max_score = Scores[:, 2][0] # Assume the first batsman has the maximum score initiallyfor score in Scores[:, 2][1:]: # Iterate through other scoresif score > max_score: max_score = score# Find indices where the third column (index 2) is equal to the maximum scoremax_score_indices = np.where(Scores[:, 2] == max_score)# Extract the corresponding rows (batsmen) and scoresmax_score_batsmen = Scores[max_score_indices]max_scores = max_score_batsmen[:, 2]# Print the maximum score(s) and corresponding batsmenprint("Maximum score in T_20-3:")for i, score inenumerate(max_scores):print(f"- Batsman {i+1}: {score}")# 2. Find the minimum score of YUVRAJ (assuming YUVRAJ is batsman 3)yuvraj_score = Scores[2, 2] # Access score of batsman 3 (index 2) in T_20-3 (index 2)min_score = yuvraj_scorefor score in Scores[:, 2]: # Iterate through all scores in column 2 (T_20-3)if score < min_score: min_score = scoreprint(f"Minimum score of YUVRAJ: {min_score}")# 3. Add an extra column with the sum of all 4 T20 Matches' scoresimport numpy as np# Sample scores arrayScores = np.array([[31, 12, 19, 53], [67, 48, 95, 83], [59, 67, 13, 59], [62, 29, 99, 88], [87, 91, 69, 76]])# Calculate the sum of all 4 T20 Matches' scores for each batsmantotal_scores = np.zeros(Scores.shape[0])for i inrange(Scores.shape[0]): total_score =0for j inrange(Scores.shape[1]): total_score += Scores[i, j] total_scores[i] = total_score# Create a new array with an extra column using concatenatenew_Scores = np.concatenate((Scores, total_scores[:, np.newaxis]), axis=1)# Print the scores with the total sum columnprint("Scores with total sum column:")print(new_Scores)
Maximum score in T_20-3:
- Batsman 1: 99
Minimum score of YUVRAJ: 13
Scores with total sum column:
[[ 31. 12. 19. 53. 115.]
[ 67. 48. 95. 83. 293.]
[ 59. 67. 13. 59. 198.]
[ 62. 29. 99. 88. 278.]
[ 87. 91. 69. 76. 323.]]